﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Data.Common;
using System.Data;
using System.Globalization;

namespace ResourceBlender_Express {
    /// <summary>
    /// Allows duplication of all translations from one language to another.
    /// </summary>
    public partial class WinCreateVariant : Window {
        private bool success = false;
        /// <summary>
        /// Gets whether the translation was completed successfully.
        /// </summary>
        /// <value><c>true</c> if successful; otherwise, <c>false</c>.</value>
        public bool Success { get { return success; } }

        /// <summary>
        /// Initializes a new <see cref="WinCreateVariant"/>.
        /// </summary>
        public WinCreateVariant() {
            InitializeComponent();
        }

        /// <summary>
        /// Loads the list of unique languages when the window loads.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void Window_Loaded(object sender, RoutedEventArgs e) {
            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += (s, dwe) => {
                Database db = new Database();
                try {
                    dwe.Result = db.LoadUniqueLanguages();
                } catch(Exception ex) {
                    dwe.Result = "Error connecting to the database: " + ex.Message;
                } finally {
                    if(db != null) {
                        try {
                            db.CloseConnection();
                        } catch { }
                    }
                }
            };
            worker.RunWorkerCompleted += (s, rwe) => {
                SetStatus(null, false);
                if(rwe.Result is ObservableSortedDictionary<string, CultureInfo>) {
                    ObservableSortedDictionary<string, CultureInfo> languages = rwe.Result as ObservableSortedDictionary<string, CultureInfo>;
                    if(languages.Count == 0) {
                        DialogBox.Show(this, "No resources exist. Before creating a language variant, at least one resource must be added.", "Error", DialogBox.DialogBoxType.OK, DialogBox.DialogBoxIcon.Error);
                        Close();
                    } else {
                        lstSourceLanguage.ItemsSource = languages;
                    }
                } else {
                    DialogBox.Show(this, rwe.Result.ToString(), "Error", DialogBox.DialogBoxType.OK, DialogBox.DialogBoxIcon.Error);
                }
            };
            SetStatus("Loading languages...", true);
            worker.RunWorkerAsync();
            ObservableSortedDictionary<string, CultureInfo> availableLangs = new ObservableSortedDictionary<string, CultureInfo>(new Comparers.CultureInfoEnglshNameComparer());
            foreach(CultureInfo culture in CultureInfo.GetCultures(CultureTypes.AllCultures)) {
                if(culture.Name == "") {
                    continue;
                }
                availableLangs.Add(culture.Name, culture);
            }
            lstDestinationLanguage.ItemsSource = availableLangs;
        }

        /// <summary>
        /// Starts copying between languages.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.Input.ExecutedRoutedEventArgs"/> instance containing the event data.</param>
        private void CreateVariant(object sender, ExecutedRoutedEventArgs e) {
            if(ValidateSelection()) {
                WinCreateVariantLog dlg = new WinCreateVariantLog(lstSourceLanguage.SelectedValue.ToString(), lstDestinationLanguage.SelectedValue.ToString(), radOverwrite.IsChecked == true);
                dlg.Owner = this;
                dlg.ShowDialog();
                if(dlg.Success) {
                    this.success = true;
                    Close();
                }
            }
        }

        /// <summary>
        /// Validates the selection is valid.
        /// </summary>
        /// <returns></returns>
        private bool ValidateSelection() {
            bool valid = true;
            if(lstSourceLanguage.SelectedValue == null) {
                DialogBox.ShowAlert(this, "Source language must be specified", "Error");
                valid = false;
            } else if(lstDestinationLanguage.SelectedValue == null) {
                DialogBox.ShowAlert(this, "Destination language must be specified", "Error");
                valid = false;
            } else if(lstSourceLanguage.SelectedValue == lstDestinationLanguage.SelectedValue) {
                DialogBox.ShowAlert(this, "Source and destination languages must be different", "Error");
                valid = false;
            }
            return valid;
        }

        /// <summary>
        /// Shows the help file.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.Input.ExecutedRoutedEventArgs"/> instance containing the event data.</param>
        private void ShowHelp(object sender, ExecutedRoutedEventArgs e) {
            Utils.OpenHelp("Creating.Variants.html");
        }

        /// <summary>
        /// Sets the text on the status message.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="showProgress"><c>true</c> if the progress bar should be shown, otherwise <c>false</c>.</param>
        private void SetStatus(string message, bool showProgress) {
            prgStatus.Visibility = showProgress ? Visibility.Visible : Visibility.Hidden;
            if(message == null) {
                lblStatus.Visibility = Visibility.Hidden;
            } else {
                lblStatus.Visibility = Visibility.Visible;
                lblStatus.Content = message;
            }
        }

        /// <summary>
        /// Closes the window.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.Input.ExecutedRoutedEventArgs"/> instance containing the event data.</param>
        private void CloseWindow(object sender, ExecutedRoutedEventArgs e) {
            Close();
        }
    }
}
